<template>
  <el-card>
    <div slot="header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <!-- 主体内容 -->
    <div class="filter-bar">
      <div class="l-form">
        <el-input placeholder="请输入内容" size="small" v-model="query">
          <el-button
            slot="append"
            icon="el-icon-search"
            @click="search"
          ></el-button>
        </el-input>
      </div>
      <el-button
        type="primary"
        icon="el-icon-search"
        size="small"
        @click="isshow = true"
        >添加</el-button
      >
    </div>
    <!-- 表格区域 -->
    <div class="tab-list">
      <el-table :data="userList" border stripe>
        <el-table-column
          prop="username"
          label="用户名"
          width="80px"
        ></el-table-column>
        <el-table-column prop="email" label="邮箱"> </el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态" prop="mg_state" width="80px">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeStatus(scope.row.id, $event)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="create_time" label="注册时间">
          <template slot-scope="scope">
            {{ scope.row.create_time | formateTime("YYYY/MM/DD") }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="scope">
            <!-- 修改 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="edit(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="del(scope.row.id)"
            ></el-button>
            <!-- 角色修改 -->
            <el-button
              type="warning"
              size="small"
              circle
              icon="el-icon-setting"
              @click="setRole(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- f分页 -->
      <div>
        <el-pagination
          background
          @size-change="sizeChange"
          @current-change="pageChange"
          :current-page="pagenum"
          :page-sizes="[1, 2, 3, 4, 5, 6]"
          :page-size="pagesize"
          layout="prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </div>

    <!-- 添加弹框 -->
    <el-dialog title="添加用户" :visible.sync="isshow" width="40%">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        size="normal"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="adduser">立即创建</el-button>
          <el-button @click="resetuser('ruleForm')">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 修改用户 -->
    <el-dialog title="编辑用户" :visible.sync="editisshow" width="40%">
      <el-form
        :model="editruleForm"
        :rules="rules"
        ref="editruleForm"
        label-width="100px"
        size="normal"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editruleForm.mobile"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="edituser">立即创建</el-button>
          <el-button @click="resetuser('editruleForm')">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 角色修改 -->
    <el-dialog title="角色分配" :visible.sync="setRoleShow" width="30%">
      <p>用户名：{{ roleInfo.username }}</p>
      <br />
      <p>角色名：{{ roleInfo.role_name }}</p>
      <br />
      <p>
        授权角色：
        <el-select v-model="rid" placeholder="请选择">
          <el-option value="" label="请选择"> </el-option>
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </p>
      <br />
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleShow = false">取 消</el-button>
        <el-button type="primary" @click="setRoleSubmit">确 定</el-button>
      </span>
    </el-dialog>
  </el-card>
</template>

<script>
// 定义校验规则
let email = (rule, value, callback) => {
  if (value) {
    let reg = /^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/;
    if (reg.test(value)) {
      callback();
    } else {
      callback(new Error("请输入邮箱"));
    }
  } else {
    callback();
  }
};
let mobile = (rule, value, callback) => {
  if (value) {
    let reg = /^1(3|4|5|6|7|8|9)\d{9}$/;
    if (reg.test(value)) {
      callback();
    } else {
      callback(new Error("请输入手机"));
    }
  } else {
    callback();
  }
};

export default {
  data() {
    return {
      query: "", //查询参数
      pagenum: 1,
      pagesize: 4,
      userList: [],
      total: 0,
      isshow: false,
      editisshow: false,
      ruleForm: {
        //添加用户信息
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      editruleForm: {
        //编辑用户信息
        username: "",
        email: "",
        mobile: ""
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" }
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        email: [{ validator: email, trigger: "blur" }],
        mobile: [{ validator: mobile, trigger: "blur" }]
      },
      setRoleShow: false,
      roleInfo: [],
      roleList: [],
      rid: ""
    };
  },
  created() {
    this.getuserList();
    this.getRoleList();
  },
  methods: {
    async getuserList() {
      let { data: res } = await this.$axios.get("users", {
        params: {
          query: this.query,
          pagenum: this.pagenum,
          pagesize: this.pagesize
        }
      });
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.userList = res.data.users;
      this.total = res.data.total;
    },
    // 分页
    sizeChange(val) {
      this.pagesize = val;
      this.getuserList();
    },
    pageChange(val) {
      this.pagenum = val;
      this.getuserList();
    },
    //   搜索
    search() {
      this.pagenum = 1;
      this.getuserList();
    },
    // 创建
    adduser() {
      // 验证表单数据
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return;
        //   验证正确
        let { data: res } = await this.$axios.post("users", this.ruleForm);
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.$message.success("添加成功");
        this.getuserList();
        this.isshow = false;
      });
    },

    // 编辑用户
    async edit(id) {
      this.editisshow = true;
      let { data: res } = await this.$axios.get("users/" + id);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success("获取成功");
      this.editruleForm = res.data;
    },
    edituser() {
      this.$refs.editruleForm.validate(async valid => {
        if (!valid) return;
        let { data: res } = await this.$axios.put(
          "users/" + this.editruleForm.id,
          this.editruleForm
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.getuserList();
        this.editisshow = false;
      });
    },

    // 取消
    resetuser(val) {
      this.$refs[val].resetFields();
      this.isshow = false;
      this.editisshow = false;
    },
    // 状态
    async changeStatus(val, status) {
      let { data: res } = await this.$axios.put(`users/${val}/state/${status}`);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success("修改状态成功");
    },
    // 删除用户
    async del(id) {
      try {
        await this.$confirm("确认删除?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        });
        let { data: res } = await this.$axios.delete("users/" + id);
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success("删除成功");
        // 页数判断
        if (this.pagenum !== 1 && this.userList.length === 1) {
          this.pagenum--;
        }
        this.getuserList();
      } catch (error) {
        return this.$message.info("取消删除");
      }
    },
    // 获取角色
    async getRoleList() {
      let { data: res } = await this.$axios.get("roles");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      console.log(res);
      this.roleList = res.data;
    },
    setRole(row) {
      this.roleInfo = row;
      this.setRoleShow = true;
    },
    async setRoleSubmit() {
      let { data: res } = await this.$axios.put(
        `users/${this.roleInfo.id}/role`,
        {
          rid: this.rid
        }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      (this.setRoleShow = false), this.getuserList();
    }
  }
};
</script>

<style lang="less" scoped>
</style>